<template>
  <div class="sync-data-container layout-container">
    <HeaderComponent title="数据同步管理" :loading="isLoading">
      <template #actions>
        <a-space>
          <a-button @click="handleBack">
            <template #icon><ArrowLeftOutlined /></template>
            返回态势对象
          </a-button>
          <a-button type="primary" @click="handleCreateDataSource">
            <template #icon><PlusOutlined /></template>
            新建数据源
          </a-button>
        </a-space>
      </template>
    </HeaderComponent>

    <!-- 统计卡片 -->
    <StatisticsCards :statistics="statistics" />

    <!-- 选项卡 -->
    <a-tabs v-model:activeKey="activeTab" class="content-tabs" @change="handleTabChange">
      <!-- 数据源管理 -->
      <a-tab-pane key="datasources" tab="数据源管理">
        <DataSourceTable
          :data-sources="dataSources"
          :loading="dataSourcesLoading"
          :pagination="dataSourcePagination"
          :filters="dataSourceFilters"
          @load-data-sources="loadDataSources"
          @test-connection="handleTestConnection"
          @view-tables="handleViewTables"
          @create-sync-task="handleCreateSyncTask"
          @edit-data-source="handleEditDataSource"
          @delete-data-source="handleDeleteDataSource"
          @pagination-change="handleDataSourcePaginationChange"
          @filter-change="handleDataSourceFilterChange"
        />
      </a-tab-pane>

      <!-- 同步任务管理 -->
      <a-tab-pane key="synctasks" tab="同步任务管理">
        <SyncTaskTable
          :sync-tasks="syncTasks"
          :loading="syncTasksLoading"
          :pagination="syncTaskPagination"
          :filters="syncTaskFilters"
          :selected-row-keys="selectedRowKeys"
          :row-selection="rowSelection"
          @load-sync-tasks="loadSyncTasks"
          @execute-task="handleExecuteTask"
          @batch-execute-tasks="handleBatchExecute"
          @view-task-detail="handleViewTaskDetail"
          @view-logs="handleViewLogs"
          @edit-task="handleEditTask"
          @toggle-task="handleToggleTask"
          @delete-task="handleDeleteTask"
          @pagination-change="handleSyncTaskPaginationChange"
          @filter-change="handleSyncTaskFilterChange"
        />
      </a-tab-pane>

      <!-- 同步日志 -->
      <a-tab-pane key="synclogs" tab="同步日志">
        <SyncLogTable
          :sync-logs="syncLogs"
          :loading="syncLogsLoading"
          :pagination="syncLogPagination"
          :filters="syncLogFilters"
          @load-sync-logs="loadSyncLogs"
          @view-log-detail="handleViewLogDetail"
          @retry-execution="handleRetryExecution"
          @pagination-change="handleSyncLogPaginationChange"
          @filter-change="handleSyncLogFilterChange"
        />
      </a-tab-pane>
    </a-tabs>

    <!-- 数据源表结构查看模态框 -->
    <TableStructureModal
      v-model:open="modals.tableStructure.visible"
      :data-source="modals.tableStructure.dataSource"
      @refresh="loadDataSources"
    />

    <!-- 数据源创建/编辑模态框 -->
    <DataSourceFormModal
      v-model:visible="modals.dataSourceForm.visible"
      :data-source="modals.dataSourceForm.dataSource"
      :is-edit="modals.dataSourceForm.isEdit"
      @success="handleDataSourceSuccess"
    />

    <!-- 同步任务创建模态框 -->
    <SyncTaskFormModal
      v-model:open="modals.syncTaskForm.visible"
      :data-source="modals.syncTaskForm.dataSource"
      @success="handleSyncTaskSuccess"
    />

    <!-- 同步任务详情模态框 -->
    <SyncTaskDetailModal
      v-model:visible="modals.taskDetail.visible"
      :task="modals.taskDetail.task"
    />

    <!-- 同步日志详情模态框 -->
    <SyncLogDetailModal
      v-model:visible="modals.logDetail.visible"
      :log="modals.logDetail.log"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'

// 组件导入
import HeaderComponent from '@/components/HeaderComponent.vue'
import StatisticsCards from '@/components/sync/StatisticsCards.vue'
import DataSourceTable from '@/components/sync/DataSourceTable.vue'
import SyncTaskTable from '@/components/sync/SyncTaskTable.vue'
import SyncLogTable from '@/components/sync/SyncLogTable.vue'

// 模态框组件导入
import TableStructureModal from '@/components/sync/TableStructureModal.vue'
import DataSourceFormModal from '@/components/sync/DataSourceFormModal.vue'
import SyncTaskFormModal from '@/components/sync/SyncTaskFormModal.vue'
import SyncTaskDetailModal from '@/components/sync/SyncTaskDetailModal.vue'
import SyncLogDetailModal from '@/components/sync/SyncLogDetailModal.vue'

// Composables 导入
import {
  useDataSources,
  useSyncTasks,
  useSyncLogs,
  useStatistics,
  useModals
} from '@/composables/useSyncData'

import syncApi from '@/apis/sync_api'

const router = useRouter()

// 响应式状态
const activeTab = ref('datasources')

// 使用 Composables
const {
  dataSources,
  loading: dataSourcesLoading,
  pagination: dataSourcePagination,
  filters: dataSourceFilters,
  loadDataSources,
  testConnection,
  deleteDataSource,
  handlePaginationChange: handleDataSourcePaginationChange,
  handleFilterChange: handleDataSourceFilterChange
} = useDataSources()

const {
  syncTasks,
  loading: syncTasksLoading,
  pagination: syncTaskPagination,
  filters: syncTaskFilters,
  selectedRowKeys,
  rowSelection,
  loadSyncTasks,
  executeTask,
  batchExecuteTasks,
  deleteTask,
  toggleTask,
  handlePaginationChange: handleSyncTaskPaginationChange,
  handleFilterChange: handleSyncTaskFilterChange
} = useSyncTasks()

const {
  syncLogs,
  loading: syncLogsLoading,
  pagination: syncLogPagination,
  filters: syncLogFilters,
  loadSyncLogs,
  handlePaginationChange: handleSyncLogPaginationChange,
  handleFilterChange: handleSyncLogFilterChange
} = useSyncLogs()

const {
  statistics,
  loading: statisticsLoading,
  loadStatistics
} = useStatistics()

const { modals, openModal, closeModal } = useModals()

// 计算属性：全局加载状态
const isLoading = computed(() =>
  dataSourcesLoading.value ||
  syncTasksLoading.value ||
  syncLogsLoading.value ||
  statisticsLoading.value
)

// 事件处理函数
const handleBack = () => {
  router.push('/situation')
}

const handleCreateDataSource = () => {
  openModal('dataSourceForm')
}

const handleTestConnection = async (dataSourceId) => {
  await testConnection(dataSourceId)
}

const handleViewTables = (dataSource) => {
  openModal('tableStructure', { dataSource })
}

const handleCreateSyncTask = (dataSource) => {
  if (!dataSource) {
    message.error('数据源信息缺失，无法创建同步任务')
    return
  }
  openModal('syncTaskForm', { dataSource })
}

const handleEditDataSource = (dataSource) => {
  openModal('dataSourceForm', { dataSource, isEdit: true })
}

const handleDeleteDataSource = async (id) => {
  await deleteDataSource(id)
}

const handleExecuteTask = async (task) => {
  await executeTask(task.id)
}

const handleBatchExecute = async (taskIds) => {
  await batchExecuteTasks(taskIds)
}

const handleViewTaskDetail = (task) => {
  openModal('taskDetail', { task })
}

const handleViewLogs = (task) => {
  // 切换到日志选项卡并筛选该任务的日志
  activeTab.value = 'synclogs'
  syncLogFilters.task_id = task.id
  loadSyncLogs()
}

const handleEditTask = (task) => {
  // 这里应该打开编辑任务的模态框，暂时用详情模态框代替
  openModal('taskDetail', { task })
}

const handleToggleTask = async (task) => {
  await toggleTask(task)
}

const handleDeleteTask = async (id) => {
  await deleteTask(id)
}

const handleViewLogDetail = (log) => {
  openModal('logDetail', { log })
}

const handleRetryExecution = async (log) => {
  try {
    const response = await syncApi.executeSyncTask(log.sync_task.id)
    message.success(`重试任务已启动，执行ID：${response.execution_id}`)

    // 刷新日志列表
    setTimeout(() => {
      loadSyncLogs()
    }, 1000)
  } catch (error) {
    message.error('重试失败：' + (error.message || '未知错误'))
  }
}

const handleDataSourceSuccess = () => {
  closeModal('dataSourceForm')
  loadDataSources()
}

const handleSyncTaskSuccess = () => {
  closeModal('syncTaskForm')
  loadSyncTasks()
}

// 标签页切换事件
const handleTabChange = (activeKey) => {
  activeTab.value = activeKey

  // 根据标签页加载相应的数据
  switch (activeKey) {
    case 'datasources':
      if (dataSources.length === 0) {
        loadDataSources()
      }
      break
    case 'synctasks':
      if (syncTasks.length === 0) {
        loadSyncTasks()
      }
      break
    case 'synclogs':
      if (syncLogs.length === 0) {
        loadSyncLogs()
      }
      break
  }
}

// 生命周期
onMounted(() => {
  loadStatistics()
  loadDataSources()
})
</script>

<style scoped>
.sync-data-container {
  padding: 0;
}

.content-tabs {
  background: white;
  border-radius: 8px;
  padding: 16px;
  min-height: 600px;
}

/* 优化标签页样式 */
:deep(.ant-tabs-content-holder) {
  padding: 0;
}

:deep(.ant-tabs-tab) {
  font-weight: 500;
  padding: 12px 16px;
}

:deep(.ant-tabs-tab-active) {
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-tabs {
    padding: 8px;
  }

  :deep(.ant-tabs-tab) {
    padding: 8px 12px;
    font-size: 14px;
  }
}

/* 加载状态优化 */
:deep(.ant-spin-container) {
  min-height: 200px;
}

/* 动画效果 */
:deep(.ant-tabs-tabpane) {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>